<template>
	<view :style="[AppSkinVar]">
		<e-loading-page :loading="pageLoading">
			<template #icon>
				<loader></loader>
			</template>
		</e-loading-page>
		<view class="e-p-20">
			<e-search height="60rpx" :show-action="false" :placeholder="$t('user.addressInputTips')" v-model="keyword" @search="search"></e-search>
		</view>
		<view class="e-p-20" v-for="(item, index) in addressList" :key="item.id" @tap="select(item, index)">
			<view class="e-flex e-flex-between e-m-b-2">
				<text class="fw-600">{{ item.name }}</text>
				<radio :value="`${index}`" :checked="addressIndex === index" :color="AppSkin.primary" />
			</view>
			<view>
				<text class="e-font-24 c-secondary">{{ item.vicinity }}</text>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';
import { useI18n, useCurrentInstance } from '@/common/hooks';
import { onLoad } from '@dcloudio/uni-app';
import { getLocation, defaultLatitude, defaultLongitude, nearbyAddress, searchAddress } from '@/common/utils/map/index';

const ctx = useCurrentInstance();

const addressList = ref([]);
const latitude = ref(defaultLatitude);
const longitude = ref(defaultLongitude);
const keyword = ref('');
const addressIndex = ref(-1);
const pageLoading = ref(false);

const getUserLocation = (isRefresh?: boolean) => {
	pageLoading.value = true;
	let userGeolocation = uni.getStorageSync('userGeolocation');
	if (userGeolocation && !isRefresh) {
		latitude.value = userGeolocation.latitude;
		longitude.value = userGeolocation.longitude;
		getNearbyAddress();
	} else {
		getLocation(ctx.$t('nearby.openGPS'), ctx.$t('nearby.GPSErr'), false).then((res) => {
			latitude.value = res.latitude;
			longitude.value = res.longitude;
			getNearbyAddress();
		});
	}
};
const getNearbyAddress = () => {
	nearbyAddress({
		latitude: latitude.value,
		longitude: longitude.value,
		keyword: keyword.value
	}).then((res) => {
		pageLoading.value = false;
		addressIndex.value = -1;
		addressList.value = res;
	});
};
const search = () => {
	pageLoading.value = true;
	if (keyword.value) {
		searchAddress({
			latitude: latitude.value,
			longitude: longitude.value,
			keyword: keyword.value
		}).then((res) => {
			pageLoading.value = false;
			addressIndex.value = -1;
			addressList.value = res;
		});
	} else {
		getNearbyAddress();
	}
};
const select = (data, index) => {
	addressIndex.value = index;
	const eventChannel = ctx.getOpenerEventChannel();
	eventChannel.emit('getUserNearbyAddress', {
		vicinity: data.vicinity,
		latitudes: data.geometry.location.lat,
		longitudes: data.geometry.location.lng,
		data
	});

	ctx.$back();
};

watch(keyword.value, (newVal) => {
	search();
});
onLoad(() => {
	getUserLocation();
});
</script>

<style>
page {
	background: #ffffff;
}
</style>
